package at.fhj.swd.pse.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import at.fhj.swd.pse.entities.Community;
import at.fhj.swd.pse.entities.User;

/**
 * Mockup for CommunityService DAO.
 * Defined as private to avoid ambiguous CommunityDAOs for injection.
 * @author Helmut Kopf
 *
 */
public final class CommunityDAOMock
	implements CommunityDAO
{
	private List<Community> m_communities = new ArrayList<Community>();
	
	public CommunityDAOMock() {		
	}

	private int m_nextId = 0;	
	
	public Community insert(Community entity)
	{
		m_communities.add(entity);
		entity.setID(getNextId());
		return entity;
	}

	@Override
	public Community get(int id) 
	{
		int ii = indexOf(id);
		
		if (ii != -1)
		{
			return m_communities.get(ii);
		}
		
		return null;
	}
	
	@Override
	public List<Community> getAll() 
	{		
		return Collections.unmodifiableList(m_communities);
	}

	@Override
	public void remove(Community entity) 
	{		
		int ii = indexOf(entity.getID());
		
		if (ii != -1)
		{
			m_communities.remove(ii);
		}			
	}

	@Override
	public Community update(Community entity) 
	{
		int ii = indexOf(entity.getID());
		
		if (ii != -1)
		{
			m_communities.set(ii, entity);
			return entity;
		}
		else
		{
			return insert(entity);
		}			
	}

	@Override
	public void addUserToCommunity(int userId, int communityId)
	{		
		Community community = get( communityId );
		
		if( community != null )
		{
			User user = new User();
			user.setId(userId);
			community.addMember(user);
		}
	}
	
	private int indexOf(int id)
	{
		for (int ii = 0; ii < m_communities.size(); ii++)
		{			
			if (m_communities.get(ii).getID() == id)
			{
				return ii;
			}
		}
		
		return -1;
	}
	
	private int getNextId()
	{
		return (m_nextId++);
	}

	@Override
	public void releaseCommunity(int communityId) {
		
		int ii = indexOf(communityId);
		
		if (ii != -1)
		{
			m_communities.get(ii).setReleased(true);
		}			
	}	
}